package com.qms.qep.controller;

import java.util.List;
import java.util.Map;
import java.util.HashMap;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.qms.common.core.controller.BaseController;
import com.qms.common.core.domain.AjaxResult;
import com.qms.common.core.page.TableDataInfo;
import com.qms.qep.domain.RepairTask;
import com.qms.qep.service.IRepairTaskService;
import com.qms.qep.service.IRepairEvaluationService;
import com.qms.common.utils.poi.ExcelUtil;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;

/**
 * 维修任务Controller
 */
@RestController
@RequestMapping("/qep/repair-task")
public class RepairTaskController extends BaseController {
    @Autowired
    private IRepairTaskService repairTaskService;
    
    @Autowired
    private IRepairEvaluationService repairEvaluationService;

    /**
     * 查询维修任务列表
     */
    @PreAuthorize("@ss.hasPermi('qep:repair-task:list')")
    @GetMapping("/list")
    public TableDataInfo list(RepairTask repairTask) {
        // 如果前端传入了文本状态，则转换为状态码
        if (repairTask.getStatusText() != null && !repairTask.getStatusText().isEmpty()) {
            repairTask.setStatus(RepairTask.convertStatusTextToCode(repairTask.getStatusText()));
        }
        
        startPage();
        List<RepairTask> list = repairTaskService.selectRepairTaskList(repairTask);
        
        // 将状态码转换为状态文本，方便前端展示
        for (RepairTask task : list) {
            if (task.getStatus() != null) {
                task.setStatusText(RepairTask.convertStatusCodeToText(task.getStatus()));
            }
        }
        
        return getDataTable(list);
    }

    /**
     * 获取维修任务详细信息
     */
    @PreAuthorize("@ss.hasPermi('qep:repair-task:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Integer id) {
        RepairTask repairTask = repairTaskService.selectRepairTaskById(id);
        // 设置状态文本
        if (repairTask != null && repairTask.getStatus() != null) {
            repairTask.setStatusText(RepairTask.convertStatusCodeToText(repairTask.getStatus()));
        }
        return success(repairTask);
    }
    
    /**
     * 根据不合格品ID查询维修任务
     */
    @PreAuthorize("@ss.hasPermi('qep:repair-task:query')")
    @GetMapping(value = "/nonconforming/{nonconformingId}")
    public AjaxResult getInfoByNonconformingId(@PathVariable("nonconformingId") Integer nonconformingId) {
        RepairTask repairTask = repairTaskService.selectRepairTaskByNonconformingId(nonconformingId);
        // 设置状态文本
        if (repairTask != null && repairTask.getStatus() != null) {
            repairTask.setStatusText(RepairTask.convertStatusCodeToText(repairTask.getStatus()));
        }
        return success(repairTask);
    }

    /**
     * 新增维修任务
     */
    @PreAuthorize("@ss.hasPermi('qep:repair-task:add')")
    @PostMapping
    public AjaxResult add(@RequestBody RepairTask repairTask) {
        // 如果前端传入了文本状态，则转换为状态码
        if (repairTask.getStatusText() != null && !repairTask.getStatusText().isEmpty()) {
            repairTask.setStatus(RepairTask.convertStatusTextToCode(repairTask.getStatusText()));
        }
        return toAjax(repairTaskService.insertRepairTask(repairTask));
    }

    /**
     * 修改维修任务
     */
    @PreAuthorize("@ss.hasPermi('qep:repair-task:edit')")
    @PutMapping
    public AjaxResult edit(@RequestBody RepairTask repairTask) {
        // 如果前端传入了文本状态，则转换为状态码
        if (repairTask.getStatusText() != null && !repairTask.getStatusText().isEmpty()) {
            repairTask.setStatus(RepairTask.convertStatusTextToCode(repairTask.getStatusText()));
        }
        return toAjax(repairTaskService.updateRepairTask(repairTask));
    }

    /**
     * 删除维修任务
     */
    @PreAuthorize("@ss.hasPermi('qep:repair-task:remove')")
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Integer[] ids) {
        return toAjax(repairTaskService.deleteRepairTaskByIds(ids));
    }
    
    /**
     * 删除维修任务，级联删除相关评价
     */
    @PreAuthorize("@ss.hasPermi('qep:repair-task:remove')")
    @DeleteMapping("/delete-cascade")
    @Transactional
    public AjaxResult removeCascade(@RequestParam("ids") Integer[] ids) {
        try {
            // 先删除关联的评价记录
            for (Integer id : ids) {
                repairEvaluationService.deleteRepairEvaluationByTaskId(id);
            }
            // 再删除维修任务
            return toAjax(repairTaskService.deleteRepairTaskByIds(ids));
        } catch (Exception e) {
            logger.error("级联删除维修任务失败: ", e);
            return error("删除失败: " + e.getMessage());
        }
    }
    
    /**
     * 检查维修任务是否有关联的评价记录
     */
    @GetMapping("/check-evaluation")
    public AjaxResult checkEvaluation(@RequestParam("taskId") Integer taskId) {
        try {
            int count = repairEvaluationService.countRepairEvaluationByTaskId(taskId);
            Map<String, Object> result = new HashMap<>();
            result.put("hasEvaluation", count > 0);
            result.put("count", count);
            return success(result);
        } catch (Exception e) {
            logger.error("检查维修任务关联评价失败: ", e);
            return error("查询失败: " + e.getMessage());
        }
    }
    
    /**
     * 导出维修任务数据
     */
    @PostMapping("/export")
    public void export(HttpServletResponse response, RepairTask repairTask) {
        try {
            // 设置响应头，以便前端能够正确处理响应
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setCharacterEncoding("utf-8");
            String fileName = "维修任务数据" + System.currentTimeMillis() + ".xlsx";
            response.setHeader("Content-Disposition", "attachment;filename=" + new String(fileName.getBytes("gb2312"), "ISO8859-1"));
            
            // 查询数据
            List<RepairTask> list = repairTaskService.selectRepairTaskList(repairTask);
            
            // 设置状态文本和关联对象名称
            for (RepairTask task : list) {
                if (task.getStatus() != null) {
                    task.setStatusText(RepairTask.convertStatusCodeToText(task.getStatus()));
                } else {
                    task.setStatusText("待处理"); // 确保有默认值
                }
                
                // 获取关联对象的名称，确保Excel导出时显示名称而不只是ID
                if (task.getProductId() != null) {
                    // 通过产品服务获取产品名称
                    task.setProductName(task.getProductName() != null ? 
                        task.getProductId() + "-" + task.getProductName() : String.valueOf(task.getProductId()));
                }
                
                if (task.getBatchId() != null) {
                    // 通过批次服务获取批次编号
                    task.setBatchCode(task.getBatchCode() != null ? 
                        task.getBatchId() + "-" + task.getBatchCode() : String.valueOf(task.getBatchId()));
                }
                
                if (task.getDefectId() != null) {
                    // 通过缺陷服务获取缺陷名称
                    task.setDefectName(task.getDefectName() != null ? 
                        task.getDefectId() + "-" + task.getDefectName() : String.valueOf(task.getDefectId()));
                }
            }
            
            // 导出Excel
            ExcelUtil<RepairTask> util = new ExcelUtil<>(RepairTask.class);
            util.exportExcel(response, list, "维修任务数据");
        } catch (Exception e) {
            e.printStackTrace();
            try {
                response.setContentType("application/json");
                response.setCharacterEncoding("utf-8");
                response.getWriter().write("{\"code\":500,\"msg\":\"导出失败：" + e.getMessage() + "\"}");
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
    }
    
    /**
     * 统计维修任务数量
     */
    @PreAuthorize("@ss.hasPermi('qep:repair-task:query')")
    @GetMapping("/count")
    public AjaxResult count(RepairTask repairTask) {
        // 如果前端传入了文本状态，则转换为状态码
        if (repairTask.getStatusText() != null && !repairTask.getStatusText().isEmpty()) {
            repairTask.setStatus(RepairTask.convertStatusTextToCode(repairTask.getStatusText()));
        }
        return success(repairTaskService.countRepairTask(repairTask));
    }
} 